<template>
  <div class="app-container">
    <GoodsInfoSearchQuick ref="quickSearch" @quickSearch="quickSearch" @researchTable="researchTable"/>
    <!-- 正常显示的页面及表格 -->
    <template v-if="isMain && !isMultiple && !isSingle && !isShow">
      <el-button type="primary" class="enableBatchOpt ? 'margin-right-10' : ''" @click="showAddDialog">添加</el-button>
      <el-dropdown class="margin-right-10" v-if="enableBatchOpt">
        <el-button type="primary">
          批量操作
          <i class="el-icon-arrow-down el-icon--right" />
        </el-button>
        <el-dropdown-menu slot="dropdown" style="margin-left: 10px">
          <el-dropdown-item @click.native="batchActive">设为可用</el-dropdown-item>
          <el-dropdown-item @click.native="batchInactive">设为不可用</el-dropdown-item>
          <el-dropdown-item divided @click.native="batchRemove">
            <span style="color: #ff0000;">批量删除</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </template>
    <!-- 供多选的页面及表格 -->
    <template v-if="isMultiple">
      <el-button
        v-if="multipleOptions.optType === 'add'"
        type="primary"
        @click="confirmSelection"
      >确认选择</el-button>
      <el-button
        v-if="multipleOptions.optType === 'show'"
        type="primary"
        @click="showSelectDialog"
      >新增</el-button>
      <el-button v-if="multipleOptions.optType === 'show'" type="danger" @click="removeSelection">删除</el-button>
    </template>
    <!-- 供单选的页面及表格 -->
    <template v-if="isSingle">
      <el-button type="primary" @click="confirmSelect">确认选择</el-button>
    </template>
    <!-- 所有页面的通用部分 -->
    <el-button type="primary" @click="showSearchDialog">高级搜索</el-button>
    <el-tooltip content="刷新" placement="top">
      <el-button icon="el-icon-refresh-right" type="success" circle @click="searchTable(false)"></el-button>
    </el-tooltip>
    <el-tooltip content="重置搜索" placement="top">
      <el-button icon="el-icon-refresh" type="success" circle @click="researchTable"></el-button>
    </el-tooltip>
    <GoodsInfoTable
      ref="table"
      :isSingleTable="isSingleTable"
      :isMultipleTable="isMultipleTable"
      :isOnlyShowTable="isOnlyShowTable"
      @searchTable="searchTable"
      @quickSearch="quickSearch"
      @showEditDialog="showEditDialog"
      @showDetailDialog="showDetailDialog"
      @showJoinDetailDialog="showJoinDetailDialog"
      @showJoinSearchDialog="showJoinSearchDialog"
      @showContentDialog="showContentDialog"
      @showImageOrder="showImageOrder"
      @showSkus="showSkus"
      @showDistributionRatio="showDistributionRatio"
      @showExpressTemplateDialog="showExpressTemplateDialog"
      @showExpressDetail="showExpressDetail"
    />
    <GoodsInfoAddEditDialog
      ref="addEditDialog"
      @add="add"
      @edit="edit"
      @showJoinSearchDialog="showJoinSearchDialog"
    />
    <GoodsInfoSearchDialog ref="searchDialog" @searchTable="searchTable" />
    <GoodsInfoDetailDialog ref="detailDialog" />
    <GoodsShopDetailDialog ref="GoodsShopDetailDialog" /><GoodsCategoryDetailDialog ref="GoodsCategoryDetailDialog" /><GoodsBrandDetailDialog ref="GoodsBrandDetailDialog" />
    <el-dialog title="选择数据" :visible.sync="dialog.GoodsShopMain" width="80%" append-to-body>
      <GoodsShopMain
        :isSingle="true"
        :singleOptions="{
        component: 'GoodsShopMain',
        tableKey: 'title',
        searchFormKey: 'shopTitle',
        tableKeys: ['id','title','isActive',],
        addEditFormKeys: ['shopId','shopTitle','shopIsActive',]
      }"
        @parentConfirmSelect="parentConfirmSelect"
      />
    </el-dialog><el-dialog title="选择数据" :visible.sync="dialog.GoodsCategoryMain" width="80%" append-to-body>
      <GoodsCategoryMain
        :isSingle="true"
        :singleOptions="{
        component: 'GoodsCategoryMain',
        tableKey: 'title',
        searchFormKey: 'categoryTitle',
        tableKeys: ['id','title','isActive',],
        addEditFormKeys: ['categoryId','categoryTitle','categoryIsActive',]
      }"
        @parentConfirmSelect="parentConfirmSelect"
      />
    </el-dialog><el-dialog title="选择数据" :visible.sync="dialog.GoodsBrandMain" width="80%" append-to-body>
      <GoodsBrandMain
        :isSingle="true"
        :singleOptions="{
        component: 'GoodsBrandMain',
        tableKey: 'title',
        searchFormKey: 'brandTitle',
        tableKeys: ['id','title','isActive'],
        addEditFormKeys: ['brandId','brandTitle','brandIsActive']
      }"
        @parentConfirmSelect="parentConfirmSelect"
      />
    </el-dialog>
    <ContentDialog ref="ContentDialog"/>
    <GoodsInfoPicOrderDialog ref="GoodsInfoPicOrderDialog"/>
    <el-dialog v-if="isMain" title="商品SKU管理" :visible.sync="dialog.GoodsSkuMain" width="80%" append-to-body>
      <GoodsSkuMain ref="GoodsSkuMain"/>
    </el-dialog>
    <DistributionRatioDialog ref="DistributionRatioDialog"/>
    <el-dialog v-if="isMain" title="选择运费模板" :visible.sync="dialog.ExpressTemplateMain" width="80%" append-to-body>
      <ExpressTemplateMain ref="ExpressTemplateMain" :isSingle="true" :singleOptions="{
        component: 'ExpressTemplateMain',
        goodsExpress: true
      }"
      @parentConfirmSelect="parentConfirmSelect"
      />
    </el-dialog>
    <ExpressTemplateSettingDialog ref="ExpressTemplateSettingDialog" title="查看运费详情" :onlyView="true"/>
  </div>
</template>

<script>
import * as utils from '@/utils/utils'
import GoodsInfoSearchQuick from './GoodsInfoSearchQuick'
import GoodsInfoTable from './GoodsInfoTable.vue'
import GoodsInfoAddEditDialog from './GoodsInfoAddEditDialog.vue'
import GoodsInfoSearchDialog from './GoodsInfoSearchDialog.vue'
import GoodsInfoDetailDialog from './GoodsInfoDetailDialog.vue'
import GoodsShopDetailDialog from '../GoodsShop/GoodsShopDetailDialog.vue'
import GoodsCategoryDetailDialog from '../GoodsCategory/GoodsCategoryDetailDialog.vue'
import GoodsBrandDetailDialog from '../GoodsBrand/GoodsBrandDetailDialog.vue'

import GoodsShopMain from '../GoodsShop/GoodsShopMain.vue'
import GoodsCategoryMain from '../GoodsCategory/GoodsCategoryMain.vue'
import GoodsBrandMain from '../GoodsBrand/GoodsBrandMain.vue'
import ContentDialog from '@/components/ContentDialog/ContentDialog.vue'

import GoodsInfoPicOrderDialog from './GoodsInfoPicOrderDialog.vue'

import GoodsSkuSearchDialogVue from '../GoodsSku/GoodsSkuSearchDialog.vue'

export default {
  name: 'GoodsInfoMain',
  components: {
    GoodsInfoSearchQuick,
    GoodsInfoTable,
    GoodsInfoAddEditDialog,
    GoodsInfoSearchDialog,
    GoodsInfoDetailDialog,
    GoodsShopDetailDialog,
GoodsCategoryDetailDialog,
GoodsBrandDetailDialog,

    GoodsShopMain,
GoodsCategoryMain,
GoodsBrandMain,
ContentDialog,
GoodsInfoPicOrderDialog,
GoodsSkuMain: () => import('../GoodsSku/GoodsSkuMain.vue'),
DistributionRatioDialog: () => import('@/components/DistributionRatioDialog'),
ExpressTemplateMain: () => import('../ExpressTemplate/ExpressTemplateMain.vue'),
ExpressTemplateSettingDialog: () => import('../ExpressTemplate/ExpressTemplateSettingDialog.vue')

  },
  props: {
    /** 是否主表格 */
    isMain: {
      type: Boolean,
      default: true
    },
    /** 是否供多选的表格 */
    isMultiple: {
      type: Boolean,
      default: false
    },
    /** 是否供单选的表格 */
    isSingle: {
      type: Boolean,
      default: false
    },
    /** 是否供展示的表格 */
    isShow: {
      type: Boolean,
      default: false
    },
    /** 多选表格的选项，如用于展示和用于从表格中选择添加 */
    multipleOptions: {
      optType: {
        type: String,
        default: 'show'
      }
    },
    singleOptions: {
      component: {
        type: String,
        default: ''
      },
      tableKey: {
        type: String,
        default: null
      },
      searchFormKey: {
        type: String,
        default: null
      },
      tableKeys: {
        type: Array,
        default: () => []
      },
      addEditFormKeys: {
        type: Array,
        default: () => []
      }
    }
  },
  data() {
    return {
      enableBatchOpt: utils.enableBatchOpt,
      dialog: {
        GoodsShopDetailDialog: false,
GoodsShopMain: false,
GoodsCategoryDetailDialog: false,
GoodsCategoryMain: false,
GoodsBrandDetailDialog: false,
GoodsBrandMain: false,
GoodsSkuMain: false,
ExpressTemplateMain: false

      },
      resetSearchExcludeProps: [],
      currentExpressTemplateGoodsId: null
    }
  },
  computed: {
    /** 判断是否为单选表格 */
    isSingleTable() {
      return this.isSingle || this.isShow
    },
    /** 判断是否为多选表格 */
    isMultipleTable() {
      return (this.isMain && !this.isSingle && !this.isShow) || this.isMultiple
    },
    /** 判断表格中是否仅展示用，不包含激活/冻结、编辑、删除等操作 */
    isOnlyShowTable() {
      return this.isSingle || this.isMultiple || this.isShow
    }
  },
  mounted() {},
  methods: {
    /**  搜索表格，resetSearch表示是否重置搜索 */
    searchTable(resetSearch, clearOldSelection) {
      this.$refs.quickSearch.resetForm(this.resetSearchExcludeProps)
      utils.search({
        mainComponent: this,
        url: '/goods-info/admin/pager-cond',
        resetSearch: resetSearch,
        clearOldSelection: clearOldSelection
      })
    },
    /** 重置搜索表格 */
    researchTable() {
      this.$refs.searchDialog.resetForm(this.resetSearchExcludeProps)
      this.$refs.quickSearch.resetForm(this.resetSearchExcludeProps)
      setTimeout(() => {
        this.searchTable(true)
      }, 10)
    },
    /** 快捷搜索表格 */
    quickSearch(resetSearch) {
      this.$refs.searchDialog.resetForm(this.resetSearchExcludeProps)
      utils.search({
        mainComponent: this,
        searchDialogRef: 'quickSearch',
        url: '/goods-info/admin/pager-cond',
        resetSearch: resetSearch
      })
    },
    /** 展示添加对话框 */
    showAddDialog() {
      const addEditDialog = this.$refs.addEditDialog
      addEditDialog.dialog.add = true
      addEditDialog.initDataDict()
    },
    /** 执行添加数据操作 */
    add() {
      utils.add({
        mainComponent: this,
        url: '/goods-info/admin/save'
      })
    },
    /** 展示编辑数据对话框 */
    showEditDialog(row) {
      const addEditDialog = this.$refs.addEditDialog
      addEditDialog.dialog.edit = true
      row.version = null
      row.createTime = null
      row.updateTime = null
      addEditDialog.form = row
    },
    /** 执行编辑操作 */
    edit() {
      utils.edit({
        mainComponent: this,
        url: '/goods-info/admin/update'
      })
    },
    /** 展示数据详情对话框 */
    showDetailDialog(row) {
      const detailDialog = this.$refs.detailDialog
      detailDialog.dialog.detail = true
      detailDialog.form = row
      detailDialog.getDictItemsDisplayValue()
    },
    /** 展示高级搜索对话框 */
    showSearchDialog() {
      const searchDialog = this.$refs.searchDialog
      searchDialog.dialog.search = true
    },
    /** 执行批量激活操作 */
    batchActive() {
      utils.batchActive({
        mainComponent: this,
        url: '/goods-info/admin/batch-active',
        isActive: 1
      })
    },
    /** 执行批量冻结操作 */
    batchInactive() {
      utils.batchActive({
        mainComponent: this,
        url: '/goods-info/admin/batch-active',
        isActive: 0
      })
    },
    /** 执行批量删除操作 */
    batchRemove() {
      utils.batchRemove({
        mainComponent: this,
        url: '/goods-info/admin/batch-remove'
      })
    },
    /** 展示指定关联表的数据详情 */
    showJoinDetailDialog(options) {
      const detailDialog = this.$refs[options.detailDialog]
      detailDialog.dialog.detail = true
      utils
        .doGet(options.url, {})
        .then(response => {
          detailDialog.form = response.data
          detailDialog.getDictItemsDisplayValue()
        })
        .catch(error => {})
    },
    /** 展示指定关联表的数据的搜索对话框 */
    showJoinSearchDialog(options) {
      this.dialog[options.searchDialog] = true
    },
    // ============== 多选相关操作开始 =================
    /** 展示多选表格对话框，对话框中可确认选择 */
    showSelectDialog() {},
    /** 多选表格对话框中的确认选择 */
    confirmSelection() {},
    /** 展示状态下的数据多选删除 */
    removeSelection() {},
    /** 子组件中需要触发的父组件的多选事件函数 */
    parentConfirmSelection() {},
    // ============== 多选相关操作结束 =================
    // ============== 单选相关操作开始 =================
    /** 单选表格对话框中的确认选择 */
    confirmSelect() {
      const currentRow = this.$refs.table.table.currentRow
      if (JSON.stringify(currentRow) === '{}') {
        this.$message.warning('请选择数据')
        return
      }
      this.$emit('parentConfirmSelect', {
        row: this.$refs.table.table.currentRow,
        singleOptions: this.singleOptions
      })
    },
    /** 子组件中需要触发的父组件的单选事件函数 */
    parentConfirmSelect(options) {
      const row = options.row
      const singleOptions = options.singleOptions
      if (singleOptions.goodsExpress) {
        this.saveGoodsExpress(this.currentExpressTemplateGoodsId, row.id)
        return
      }
      const addEditDialog = this.$refs.addEditDialog
      if (addEditDialog.dialog.add || addEditDialog.dialog.edit) {
        for (let index in singleOptions.tableKeys) {
          addEditDialog.form[singleOptions.addEditFormKeys[index]] =
            row[singleOptions.tableKeys[index]]
        }
        this.dialog[singleOptions.component] = false
      } else {
        this.$refs.searchDialog.searchForm[singleOptions.searchFormKey] =
          row[singleOptions.tableKey]
        this.$refs.quickSearch.searchForm[singleOptions.searchFormKey] =
          row[singleOptions.tableKey]
        this.dialog[singleOptions.component] = false
        this.searchTable()
      }
    },
    // ============== 单选相关操作结束 =================
    showContentDialog(value) {
      const ContentDialog = this.$refs.ContentDialog
      ContentDialog.content = value
      ContentDialog.dialog = true
    },
    showImageOrder(goodsInfo) {
      this.$refs.GoodsInfoPicOrderDialog.initData(goodsInfo.id)
    },
    showSkus(goodsInfo) {
      this.dialog.GoodsSkuMain = true
      this.$nextTick(() => {
        const goodsSkuMain = this.$refs.GoodsSkuMain
        const goodsSkuSeachDialog = goodsSkuMain.$refs.searchDialog
        const goodsSkuQuickSearch = goodsSkuMain.$refs.quickSearch
        const goodsSkuAddEditDialog = goodsSkuMain.$refs.addEditDialog
        goodsSkuMain.resetSearchExcludeProps = ['shopId', 'shopTitle', 'shopIsActive', 'goodsId', 'goodsTitle', 'goodsIsActive']
        goodsSkuSeachDialog.searchForm.shopId = goodsInfo.shopId
        goodsSkuSeachDialog.searchForm.shopTitle = goodsInfo.shopTitle
        goodsSkuSeachDialog.searchForm.shopIsActive = goodsInfo.shopIsActive
        goodsSkuSeachDialog.searchForm.goodsId = goodsInfo.id
        goodsSkuSeachDialog.searchForm.goodsTitle = goodsInfo.title
        goodsSkuSeachDialog.searchForm.goodsIsActive = goodsInfo.isActive
        goodsSkuQuickSearch.searchForm.shopId = goodsInfo.shopId
        goodsSkuQuickSearch.searchForm.shopTitle = goodsInfo.shopTitle
        goodsSkuQuickSearch.searchForm.shopIsActive = goodsInfo.shopIsActive
        goodsSkuQuickSearch.searchForm.goodsId = goodsInfo.id
        goodsSkuQuickSearch.searchForm.goodsTitle = goodsInfo.title
        goodsSkuQuickSearch.searchForm.goodsIsActive = goodsInfo.isActive
        goodsSkuAddEditDialog.form.shopId = goodsInfo.shopId
        goodsSkuAddEditDialog.form.shopTitle = goodsInfo.shopTitle
        goodsSkuAddEditDialog.form.shopIsActive = goodsInfo.shopIsActive
        goodsSkuAddEditDialog.form.goodsId = goodsInfo.id
        goodsSkuAddEditDialog.form.goodsTitle = goodsInfo.title
        goodsSkuAddEditDialog.form.goodsIsActive = goodsInfo.isActive
        goodsSkuMain.searchTable()
      })
    },
    showDistributionRatio(goodsInfo) {
      let distributionRatioDialog = this.$refs.DistributionRatioDialog
      distributionRatioDialog.loadData({
        goodsId: goodsInfo.id,
        goodsTitle: goodsInfo.title,
        goodsPicUrl: goodsInfo.picUrl,
        goodsIsActive: goodsInfo.isActive,
        isActive: 1,
        sortColumn: 'distributionLevel',
        sortOrder: 'asc'
      }, 'goods', goodsInfo.id)
    },
    showExpressTemplateDialog(goodsInfo) {
      this.dialog.ExpressTemplateMain = true
      this.currentExpressTemplateGoodsId = goodsInfo.id
      this.$nextTick(() => {
        const expressTemplateMain = this.$refs.ExpressTemplateMain
        const expressTemplateTable = expressTemplateMain.$refs.table
        expressTemplateTable.selectedData = []
        utils.doPostJson('/goods-express/admin/pager-cond', {
          goodsId: goodsInfo.id,
          sortColumn: 'createTime',
          sortOrder: 'asc',
          pageNo: 1,
          pageSize: 1
        }, {}).then(response => {
          if (response.data.total > 0) {
            expressTemplateTable.selectedData = [response.data.rows[0]]
          }
          expressTemplateTable.selectedDataIdProp = 'expressTemplateId'
          expressTemplateMain.searchTable(false, true)
        }).catch(error => {})
      })
    },
    saveGoodsExpress(goodsId, expressTemplateId) {
      utils.doPostQs('/goods-express/admin/save-goods-express', {
        goodsInfoId: goodsId,
        expressTemplateId: expressTemplateId 
      }, {}).then(response => {
        this.$message.success(response.message)
        this.dialog.ExpressTemplateMain = false
        this.currentExpressTemplateGoodsId = null
      }).catch(error => {})
    },
    showExpressDetail(goodsInfo) {
      utils.doPostJson('/goods-express/admin/pager-cond', {
        goodsId: goodsInfo.id,
        isActive: 1,
        pageNo: 1,
        pageSize: 1
      }, {}).then(res => {
        let rows = res.data.rows
        if (rows.length) {
          let goodsExpress = rows[0]
          let expressTemplateSettingDialog = this.$refs.ExpressTemplateSettingDialog
          expressTemplateSettingDialog.dialog.setting = true
          expressTemplateSettingDialog.loadExpressTemplateItems({
            templateId: goodsExpress.templateId,
            templateTitle: goodsExpress.templateTitle
          })
        } else {
          this.$message.warning('该商品未配置运费模板，请先配置运费模板')
        }
      }).catch(err => {})
    }
  }
}
</script>

<style>
</style>